# Plot the mean bills, laws, tightenings, and loosenings
# by political party, as calculated in parties.do

library(haven)
library(ggplot2)
library(grid)

outdir = 'output/pub/'
laws = read_stata(paste0(outdir, 'party_summary.dta'))

# convert dependent variables and political parties to factors {{{
laws$dv = factor(
    laws$dv,
    levels = c('bills', 'laws', 'laws_tighten', 'laws_loosen'),
    labels = c('Bills Introduced', 'Laws Passed', 'Tightening Laws', 'Loosening Laws')
)

laws$party = factor(
    laws$legis_control,
    levels = c(0, 1, 2),
    labels = c('Republican', 'Democrat', 'Split')
)  # }}}

# calculate upper and lower standard error bound
laws$lb = laws$mu - 1.96*laws$se
laws$ub = laws$mu + 1.96*laws$se

# subset of bill and law means
mu.bills = subset(laws, subset = dv %in% c('Bills Introduced', 'Laws Passed'))

# subset of tightening and loosening
mu.dir = subset(laws, subset = dv %in% c('Tightening Laws', 'Loosening Laws'))

# theme for all plots {{{
plt.theme = theme(
    text = element_text(family='Helvetica', colour = 'black'),
    panel.grid.minor = element_blank(),
    panel.grid.major = element_blank(),
    panel.background = element_rect(fill = 'white', colour = 'black'),
    strip.background = element_rect(fill = 'white'),
    strip.text = element_text(face = 'bold', size = 9),
    axis.ticks = element_line(size = 0.5),
    axis.title = element_text(size = 8),
    axis.text.x = element_text(size = 8, colour = 'black'),
    axis.text.y = element_text(size = 8, colour = 'black'),
    legend.key = element_rect(fill = NA, colour = NA),
    legend.title = element_text(size = 8),
    legend.text = element_text(size = 7, lineheight = 1)
)  # }}}

# graph means by political party {{{

pos = position_dodge(width=0.2)
plot.bills = ggplot(mu.bills, aes(x=party, y=mu)) +
      facet_wrap( ~ dv, scales='free_y') +
      geom_errorbar(aes(ymin = lb, ymax = ub),
                    width=0.2, size=0.3, position=pos) +
      geom_point(size=1.5, position=pos) +
      labs(x = "", y = "Mean Legislation per Year") + plt.theme

plot.dirs = ggplot(mu.dir, aes(x=party, y=mu)) +
      facet_wrap( ~ dv, scales='free_y') +
      geom_errorbar(aes(ymin = lb, ymax = ub),
                    width=0.2, size=0.3, position=pos) +
      geom_point(size=1.5, position=pos) +
      labs(x = "", y = "Mean Legislation per Year") + plt.theme

# combine the plots into a single graph
pdf(NULL)
grid.bills = ggplotGrob(plot.bills)
grid.dirs = ggplotGrob(plot.dirs)
plt = rbind(grid.bills, grid.dirs, size = 'last')
grid.newpage()
grid.draw(plt)
ggsave(paste0(outdir, 'fig/party_summary.pdf'), plot = plt, width=6.4, height=6)

# }}}
# vim: foldmethod=marker
